import { Button, Form, Input, Modal, Space } from "antd";
import React, { useState } from "react";
import { AxiosResponse } from "axios";
import { useAppDispatch, useAppSelector } from "../../../utils/store/hooks";
import { updateLogin, updateRegister } from "../../../utils/store/deviceSlice";
import { NameInput, PasswordInput, UpdateFormType, User } from "../Login/Login";
import { toast } from "../../Toast/Toast";
import { Result, userApi } from "../../../utils/backend/server";
import { updateForm as updateInput } from "../../../utils/utils/setInput";

export const CodeInput = (props: {
  code: string;
  updateForm: UpdateFormType;
  getCode: () => void;
}) => {
  return (
    <Form.Item
      label="code"
      name="code"
      rules={[{ required: false, message: "Please input your code!" }]}
    >
      <Space style={{ width: "100%" }} direction="vertical">
        <Space.Compact style={{ width: "100%" }}>
          <Input
            type="code"
            name="code"
            value={props.code}
            onChange={props.updateForm}
          />
          <Button type="primary" onClick={props.getCode}>
            Send
          </Button>
        </Space.Compact>
      </Space>
    </Form.Item>
  );
};

export type RegisterUserType = User & { code: string };

/*props: {
  show: boolean;
  close: () => void;
  showLogin: () => void;
}
*/
export const Register = () => {
  const [form, setForm] = useState<
    RegisterUserType & { [key: string]: string }
  >({
    name: "",
    code: "",
    password: "",
  });
  const dispatch = useAppDispatch();
  const info = useAppSelector((data) => data.device);
  const updateForm = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => updateInput(e, setForm);

  const check = (val: string) => {
    if (!form[val]) {
      toast("please check " + val);
      throw Error("please check " + val);
    }
    return check;
  };

  const end = (result: Result<unknown>) => {
    // ?props.close();
    if (result.success) dispatch(updateRegister(false));
    else toast(result.msg);
  };

  const handleOk = async () => {
    // console.log(form, "form");
    check("name")("password")("code");

    end(await userApi.register(form, form.code));
  };

  const forget = async () => {
    check("name")("password")("code");
    end(await userApi.forget(form, form.code));
  };

  const getCode = async () => {
    check("name");
    try {
      const res = await userApi.getCode(form);
      if (res.success) toast("mail sent!");
      else toast(res.msg);
    } catch (err) {
      toast(((err as AxiosResponse).data as Result<null>).msg + "");
    }
  };

  return (
    <Modal
      open={info.showRegister}
      onCancel={() => dispatch(updateRegister(false))}
      destroyOnClose={true}
      footer={
        <Space>
          {/* <Button color="primary" onClick={() => dispatch(updateLogin(true))}>
            login
          </Button> */}
          <Button type="primary" onClick={forget}>
            forget
          </Button>
          <Button type="primary" onClick={handleOk}>
            register
          </Button>
        </Space>
      }
    >
      <Form
        name="basic"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 600 }}
        initialValues={{ remember: true }}
        autoComplete="off"
      >
        <NameInput name={form.name} updateForm={updateForm} />
        <PasswordInput password={form.password} updateForm={updateForm} />
        <CodeInput code={form.code} updateForm={updateForm} getCode={getCode} />
      </Form>
    </Modal>
  );
};
